import asyncio


def singleton(cls):
    instances = {}

    def wrapper(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return wrapper



@singleton
class ProxyClass(object):
    proxy_dict = dict()
    #   proxy_dict = {"taiyang":[...],"qingting":[...]}
    tasks = list()

    async def background_task(self):
        from apps.sql_app.database import proxys_sql_conn
        while True:
            sql = "SELECT sources,proxy FROM `crawler_platform`.`proxy_list` WHERE  `stat` = '1' and `proxy_flag`='0'"
            rows = await proxys_sql_conn.fetch_all(query=sql)
            proxy_dict = dict()
            for row in rows:
                try:
                    proxy_dict[row[0]].append(row[1])
                except:
                    proxy_dict[row[0]] = list()
                    proxy_dict[row[0]].append(row[1])
            self.proxy_dict = proxy_dict
            await asyncio.sleep(0.5)

    async def start_proxy_task(self):
        task = asyncio.create_task(self.background_task())
        self.tasks.append(task)

    async def end_proxy_task(self):
        for task in self.tasks:
            task.cancel()
        await asyncio.gather(*self.tasks, return_exceptions=True)